<?php

namespace Frieza\Modules\Guide\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\cache\Tag\TagGuideCounter;
use Doraemon\cache\Tag\TagGuideShare;
use Doraemon\model\AdmSpecialBanner;
use Doraemon\model\PhotoJoinGuide;
use Doraemon\model\PublishGuide;
use Doraemon\model\SitemRelevance;
use Doraemon\pockets\IdSender\IdSender;
use Doraemon\service\Guide as sGuide;
use Doraemon\model\Guide as mGuide;
use Doraemon\service\MainTag;
use Doraemon\tools\Curl;
use Doraemon\tools\HhzNiceLivingUrl;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\IdParse;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use function Clue\StreamFilter\fun;


class GuideController extends Controller
{
    const GUIDE_PREVIEW_URL = 'https://m.haohaozhu.cn';
//    const DECORATION_FILE = "/home/adm_rsync_dir/decoration_clip.dic";
    const ADM_TAG_ALL_FILE = "/home/adm_rsync_dir//tags/adm_tags_all";
    //记录某篇指南给哪些用户发过消息
    const GUIDE_SEND_MSG = '/home/adm_rsync_dir/guide_send_msg.json';

    public function index(Request $request, Content $content)
    {
        $tab = new tab();
        $title = '指南编辑列表';
        Admin::script($this->buttonScript());
        $tab->add($title, $this->listData($request));

        return $content
            ->header('指南文章管理')
            ->breadcrumb(
                ['text' => $title]
            )
            ->body($tab);
    }

    public function del($id = '')
    {
        $status = false;
        $message = "操作失败，删除失败";

        try {
            $data["status"] = mGuide::STATUS_DELETE;
            $data['edittime'] = time();
            $where['id'] = $id;
            if (mGuide::update($data, $where)) {
                \Doraemon\cache\Queue::insertQueue('BodyClean/roomService', ["type" => 'guide', 'obj_id' =>$id]);
                $status = true;
                $message = "操作成功";
            }
        } catch (\Exception $e) {
            $status = false;
            $message = "操作失败,信息:" . $e->getMessage();
        } finally {
            return response()->json(compact('status', 'message'));
        }
    }

    //添加或者修改预算表
    public function create(Content $content ,$id = "")
    {
        return $content
            ->row(self::editAction($id));
    }

    //添加或者修改预算表
    public function edit(Content $content ,$id = "")
    {
        return $content
            ->row(self::editAction($id));
    }

    //修改列表
    public function editAction($id)
    {
        if($id == ''){
            $data = [];
        }else{
            $data =  mGuide::getGuide($id);
        }

        $tagFilePath = self::ADM_TAG_ALL_FILE;

        $share_info = json_decode(TagGuideShare::getGuide($id), true);
        $data['share_pic_id'] = $share_info['share']['weibo']['cover_img'] ?? '';
        $data['share_desc'] = $share_info['share']['qq']['desc'] ?? '';
        $tags = file($tagFilePath);
        $tagsAll = [
            "未打标签"
        ];

        $admTag = explode(',', $data['admin_tag']) ?? [];
        $mainTag = explode(',', $data['main_tag']) ?? [];
        $data['admin_tag'] = [];
        $data['main_tag'] = [];

        foreach ($tags as $key => $val) {
            $tagsAll[] = trim($val);
            if (in_array(trim($val), $admTag)) {
                $data['admin_tag'][] = $key+1;
            }

            if (in_array(trim($val), $mainTag)) {
                $data['main_tag'][] = $key+1;
            }
        }
        //获取指南乐高后台编辑地址，没有对应legoId则生成并保存
        $legoUrl = '';
        if (!empty($id)) {
            if (isset($data['lego_id']) && $data['lego_id']) {
                $legoUrl = Hhzurl::getLeGoAdmin($data['lego_id']);
            } else {
                $createUrl = Hhzurl::getLeGoAdminCreate();
                $query = [
//                    'id' => 84, //测试
                    'id'=> 153,
                    'name' => $id,
//                    'create_user' => 37, //测试
                    'create_user' => 1,
                    'type' => 0,
                    'status' => 10,
                ];

                $getResult = Curl::Request('post', $createUrl, ['json' => $query]);
                if ($getResult['code'] == 1) {
                    $legoId = $getResult['json']['data']['insertId'] ?? 0;
                    if (mGuide::updateGuide($id, ['lego_id' => $legoId])) {
                        $legoUrl = Hhzurl::getLeGoAdmin($legoId);
                    }
                }

            }
        }


        $form = new Form($data);
        if(!empty($id)){
            $form->hidden('id')->value($id);
        }
        $form->select('type', '专题类型')->options([0 => "指南"]);
        $form->text('title', '文章标题')->required();
        $form->radio('uid', '发布账号')->options(sGuide::AUTHERS)->help("发布者不可修改,提交不生效");
//        $form->html('<h7>'.date( "Y-m-d",$data['show_time']).' </h7>',  '推荐时间');
        $form->text("number" ,'期数');
        $form->text("share_desc" , "摘要")->required();
        $form->imgUpload('cover_pic_id_2_0', '2_0版本头图', false, ['imgType' => ImgUrl::APPTYPE_APP, 'imgSize' => ImgUrl::IMAGE_SIZE_A_PIC])->help("请上传750*375头图 | 上传图片大小请勿超过300k,小方图为100k");
        $form->imgUpload('cover_pic_id_3_2', '聚合页走马灯', false, ['imgType' => ImgUrl::APPTYPE_APP, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_NPHONE])->help("「请上传420x225走马灯封面 | 上传图片大小请勿超过300k");
        $form->imgUpload('share_pic_id', '分享图片', false, ['imgType' => ImgUrl::APPTYPE_APP, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_NPHONE])->help("请上传分享图片 | 小方图不超过30k");
        $form->hidden('hide_pic_url')->value($share_info['share']['qq']['cover_img']);
        $form->hidden('weibo_pic_id')->value($share_info['share']['weibo']['cover_img']);
        $form->multipleSelect("admin_tag", '标签')->options($tagsAll)->help("用于搜索");
        $form->multipleSelect("main_tag", '主标签')->options($tagsAll)->help("用于推荐");
        if (!empty($id)) {
            $form->html("<a href='" . $legoUrl . "' target='_blank' style='color: #337ab7;font-weight: bold;font-size: 18px;'>点击跳转编辑富文本内容</a>");
        } else {
            $form->html('<h4>请保存基础信息后，再编辑富文本内容！</h4>');
        }
        $form->action('/admin/guide/save');

        return $form->render();
    }

    //添加或者修改预算表
    public function save(Request $request)
    {
        $request = $request->all();
        $id = $request['id'] ? : "";

        $data = [];
        $data['type'] = $request['type'] ?? 0;
        $data['title'] = $request['title'] ?? '';
        if (mb_strwidth($data['title'], 'utf-8') > 60) {
            $error = new MessageBag([
                'title' => '标题长度超过60'
            ]);
            return redirect('/admin/guide/listing/edit/'.$id)->with(compact('error'));
        }
        if (empty($id)) { //编辑不能更改发布者
            $data['uid'] = $request['uid'] ?? 0;
            if (!$data['uid']) {
                $error = new MessageBag([
                    'title' => '发布者不能为空'
                ]);
                return redirect('/admin/guide/listing')->with(compact('error'));
            }
        }
        $data['number'] = $request['number'] ?? 0;
        $data['cover_pic_id_2_0'] = $request['cover_pic_id_2_0'] ?? '';
        $data['cover_pic_id_3_2'] = $request['cover_pic_id_3_2'] ?? '';
        $data['status'] = mGuide::STATUS_DRAFT;

        $guide = mGuide::getGuide($request['id']);

        if($guide && ($guide['status'] == mGuide::STATUS_NORMAL || $guide['status'] == mGuide::STATUS_EDIT)){
              $data['status'] = mGuide::STATUS_EDIT;
        }

        $tags = file(self::ADM_TAG_ALL_FILE);
        $tagsAll = [
            "未打标签"
        ];

        foreach ($tags as $val) {
            $tagsAll[] = trim($val);
        }

        $data['admin_tag'] = '';
        if ($request['admin_tag'] && is_array($request['admin_tag'])) {
            $adm = [];
            foreach ($request['admin_tag'] as $admTag) {
                if ($admTag == 0) continue;
                if ($admTag == '') continue;
                $adm[] = $tagsAll[$admTag];
            }
            $data['admin_tag'] = implode(',', $adm);
        }
        //主标签
        $data['main_tag'] = '';
        if ($request['main_tag'] && is_array($request['main_tag'])) {
            $main = [];
            foreach ($request['main_tag'] as $mainTag) {
                if ($mainTag == 0) continue;
                if ($mainTag == '') continue;
                $main[] = $tagsAll[$mainTag];
            }
            $data['main_tag'] = implode(',', $main);
        }
        if ($guide) {
            $data['edittime'] = time();
            $result = mGuide::updateGuide($id, $data);
        } else {
            // 获取新指南id
            $data['id'] = IdSender::getGuideId($data['uid']);
            //创建乐高
            $createUrl = Hhzurl::getLeGoAdminCreate();
            $query = [
//                    'id' => 84, //测试
                'id'=> 153,
                'name' => $data['id'],
//                    'create_user' => 37, //测试
                'create_user' => 1,
                'type' => 0,
                'status' => 10,
            ];

            $getResult = Curl::Request('post', $createUrl, ['json' => $query]);
            if ($getResult['code'] == 1) {
                $data['lego_id'] = $getResult['json']['data']['insertId'] ?? 0;
            }
            $data['addtime'] = time();
            $result = mGuide::addGuide($data);
            $id = $data['id'];
        }


        //分享的文案设置
        if ($result) {
            $data['id'] = $id;
            $data['share_pic_id'] = $request['share_pic_id'] ?? '';
            $data['share_desc'] = $request['share_desc'] ?? '';
            $data['hide_pic_url'] = $request['hide_pic_url'] ?? '';
            $data['weibo_pic_id'] = $request['weibo_pic_id'] ?? '';

            $qq_share = $this->getShare("qq", $data);
            $weibo_share = $this->getShare("weibo", $data);
            $wechat_share = $this->getShare("wechat", $data);
            $wechat_moments_share = $this->getShare("wechat_moments", $data);
            $share['share']['wechat'] = $wechat_share;
            $share['share']['wechat_moments'] = $wechat_moments_share;
            $share['share']['weibo'] = $weibo_share;
            $share['share']['qq'] = $qq_share;

            TagGuideShare::set($id, json_encode($share));

            $success = new MessageBag([
                'title' => '操作成功'
            ]);
            return redirect('/admin/guide/listing')->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '操作失败'
            ]);
            return redirect('/admin/guide/listing/edit/'.$id)->with(compact('error'));
        }
    }

    private function listData(Request $request)
    {
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 10);
        $search = $request->input('search', []);

        $query["AND"]['type'] = 0;
        if (isset($search['uid']) && is_numeric($search['uid'])) {
            $query["AND"]['uid'] = $search['uid'];
        }

        if (!empty($search['id'])) {
            $query["AND"]['id'] = $search['id'];
        }

        if (!empty($search['status'])) {
            $query["AND"]['status'] = $search['status'];
        } else {
            $search['status'] = [mGuide::STATUS_DRAFT, mGuide::STATUS_NORMAL,  mGuide::STATUS_EDIT];
            $query["AND"]['status'] = [mGuide::STATUS_NORMAL, mGuide::STATUS_DRAFT, mGuide::STATUS_EDIT];
        }

        if (!empty($search['keyword'])) {
            $query["OR"]['title[~]'] = "%" . $search['keyword'] . "%";;
            $query["OR"]['admin_tag[~]'] = "%" . $search['keyword'] . "%";;

        }

        $guide = $this->getGuideData($query, $page, $pageSize);

        foreach ($guide['data'] as  &$val) {
            $val['guide_id'] = $val['id'];
        }

        $gridModel = new pGridDataModel($guide['data'], $guide['total'], ['perPage' => $pageSize, '']);

        $gridModel->setKeyType('string');
        $gridModel->setKeyName("guide_id");

        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($gridModel, $search) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->paginate($gridModel->getPerPage());

            //筛选
            $grid->filter(function (Grid\Filter $filter) use ($search) {
                // 去掉默认的id过滤器
                $filter->disableIdFilter();
                $filter->column(4, function (Grid\Filter $filter) use ($search) {
                    $filter->equal('search.uid', '发布账号')->select(sGuide::AUTHERS)->default($search['uid']);
                    $filter->in('search.status', "状态")->checkbox([
                        mGuide::STATUS_DRAFT   => '草稿',
                        mGuide::STATUS_NORMAL  => '已发布',
                        mGuide::STATUS_EDIT    => '重新编辑',
                    ])->default($search['status']);
                });
                $filter->column(4, function (Grid\Filter $filter) use ($search) {
                    $filter->equal('search.id', 'id')->default($search['id']);
                    $filter->equal('search.keyword', '关键字')->default($search['keyword']);
                });

                //条件展开
                if ($search) $filter->expand();
            });

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableView();
            });

            $grid->column('guide_id', "专题Id");
            $grid->column('type', "类型")->display(function(){
                return "指南";
            });
            $grid->column('uid', "作者")->using(sGuide::AUTHERS);
            $grid->column('number', "期数")->display(function ($number) {
                return "第{$number}期";
            });
            $grid->column('title', "标题");
            $grid->column('admin_tag', "标签");
            $grid->column('addtime', "添加时间")->display(function ($addtime) {
                return date("Y-m-d H:i:s", $addtime);
            });
            $grid->column('cron_date', "定时时间")->display(function ($cron_date) {
                if ($cron_date == 0) {
                    return "未定时";
                }
                return date("Y-m-d H:i:s", $cron_date);
            });
            $grid->column('show', "浏览")->display(function () {
                $url = self::GUIDE_PREVIEW_URL."/community/guide/detail?guide_id=".$this->guide_id."&preview=1";
                $app = self::GUIDE_PREVIEW_URL."/guideDetail/{$this->guide_id}.html";

                return "<a href=" .$url. " target='_blank' >"."分享页"."</a> |<br/>"."<a href=" .$app. " target='_blank' >"."APP"."</a>";
            });
            $grid->column('status', "状态")->using(mGuide::GUIDE_STATUS_TEXT);
            $grid->column('publish', '发布操作')->display(function () {
                $publish_btn = "<a href='javascript:;' class='btn btn-default publish'  data-id='$this->guide_id'>发布</a>";
                $cron_btn = "<a href='listing/cron/publish/$this->guide_id' class='btn btn-default'>定时发布</a>";
                return $publish_btn . "<br><br>" . $cron_btn;
            });

            $grid->column('edit_text', "编辑富文本")->display(function () {
                if ($this->lego_id) {
                    $legoUrl = Hhzurl::getLeGoAdmin($this->lego_id);
                    return "<a href=" .$legoUrl. " target='_blank' >"."编辑富文本"."</a>";
                }
            });

            $grid->disableRowSelector(false);

            $grid->actions(function ($actions) {
                $actions->append('<a href="/admin/guide/listing/edit/' . $actions->row->guide_id . '" class="fa fa-edit">编辑</a>');
                $actions->disableView();
                $actions->disableEdit();


            });
        });

        return $listGrid->render();

    }

    private function getGuideData($query, $page, $pageSize)
    {
        $guide = [
            "total" => 0,
            "data" => []
        ];

        $query["ORDER"] = [
            'number' => "DESC",
            'addtime' => "DESC"
        ];

        $query["LIMIT"] = [ ($page - 1) * $pageSize, $pageSize];

        $list = mGuide::select("*" , $query);

        unset($query["LIMIT"]);
        unset($query["ORDER"]);
        $count = mGuide::count($query);

        if ($list && is_array($list)){
            $guide = [
                "total" => $count,
                "data" => $list
            ];
        }
        return $guide;
    }

    // 设置分享文案 (新上传或者之前有分享图片，就用之前的，如果都没有就用卡片中photo的图片
    //（增加photo图片逻辑在乐高添加完内容之后的接口调用中）)
    private function getShare($pre = '', $guideInfo = array())
    {
        $share = array();
        $share['url'] = Hhzurl::h5ZhinanShow($guideInfo['id']);
        if ($pre == 'weibo') {
            $share['title'] = "我从@好好住APP 分享了「{$guideInfo['title']}」戳这里看:";
        } else {
            $share['title'] = $guideInfo['title'] . "| 好好住 APP";
            $share['desc'] = $guideInfo['share_desc'] ?? '';
        }
        if (!empty($guideInfo['share_pic_id'])) {
            if ($pre == "weibo") {
                $share['cover_img'] = $guideInfo['share_pic_id'];
            } else {
                $share['cover_img'] = ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $guideInfo['share_pic_id'], ImgUrl::IMAGE_SIZE_SQ_THUMB);
            }
        } else {
            if ($guideInfo['hide_pic_url']) {
                if ($pre == "weibo") {
                    $share['cover_img'] = $guideInfo["weibo_pic_id"];
                } else {
                    $share['cover_img'] = $guideInfo["hide_pic_url"];
                }
            }
        }

        if (empty($share['cover_img'])) {
            $error = new MessageBag([
                'title' => '分享图片链接缺失'
            ]);
            return redirect('/admin/guide/listing/edit/'.$guideInfo['id'])->with(compact('error'));
        }

        return $share;
    }

    public function buttonScript()
    {
        return <<<SCRIPT
            $('.publish').click(function() {
                var id = $(this).data('id');
                console.log(id);    
                 $.ajax({
                     type:"post",
                     url:"listing/publish",
                     data:{id:id},
                     success:function(data){
                         if (data.code == 0) {
                            toastr.success(data.msg, null, {
                                timeOut : 1000
                            });  
                         } else {
                            toastr.success(data.msg, null, {
                                timeOut : 1000
                            });  
                         }
                     }
                 });
            });
            SCRIPT;
    }

    // 专题发布
    public function publish(Request $request)
    {
        try {
            $request = $request->all();
            $guide_id = $request['id'];
            $data['code'] = 0;
            $data['msg'] = '发布失败';

            if (empty($guide_id)) {
                $data['code'] = 1;
                $data['msg'] = '专题id错误';
                return $data;
            }
            $guide = mGuide::get('*', ['id' => $guide_id]);
            //获取指南创建者
            $zh_nick = sGuide::AUTHERS[$guide['uid']] ?? "好好住";

            // 提取出文章中选取的图片
            $pattern = '/data-photo-id=\"(\w{16})\"/U';
            preg_match_all($pattern, $guide['content'], $matches_photo);

            if ($matches_photo && is_array($matches_photo)) {
                // 判断在专题和图片关系中是否存有记录，如果有记录说明是修改已发布专题，否则是第一次发布专题
                $relation_data = PhotoJoinGuide::select('*', ['guide_id' => $guide_id]);

                if ($relation_data && is_array($relation_data)) {
                    $photo_ids = [];
                    foreach ($relation_data as $item_relation) {
                        $photo_ids[] = $item_relation['photo_id'];
                    }
                    // 对比上一个版本新增的图片
                    $add_photo_ids = array_diff($matches_photo[1], $photo_ids);
                    if ($add_photo_ids && is_array($add_photo_ids)) {
                        $this->handlePhotoRelation($add_photo_ids, $guide_id, $guide['uid']);
                    }
                    // 对比上一个版本删除的图片
                    $del_photo_ids = array_diff($photo_ids, $matches_photo[1]);
                    if ($del_photo_ids && is_array($del_photo_ids)) {
                        foreach ($del_photo_ids as $photo_id) {
                            $where = [];
                            $where['photo_id'] = $photo_id;
                            $where['guide_id'] = $guide_id;
                            PhotoJoinGuide::delete($where);

                            // 删除图片信息缓存
                            \Doraemon\cache\Queue::insertQueue('Photo/delCacheById', ['photo_id' => $photo_id]);
                        }
                    }
                } else {
                    $matches_photo[1] = array_unique($matches_photo[1]);
                    $this->handlePhotoRelation($matches_photo[1], $guide_id, $guide['uid']);
                }
            }

            //获取文章关联的文章，活动，问题，话题等等。。
            if ($guide && is_array($guide)) {
                $pattern = '/\<img\s+src=\"\w.+\".+\>/U';
                preg_match_all( $pattern, $guide['content'], $match_all );

                if ($match_all[0] && is_array($match_all[0])){
                    $relative_id_hash = [];
                    foreach ($match_all[0] as $img){
                        $sub_pattern = '/<img.+src=\"\w.+\".+data-(.*?)-id=\"(\w+)\"?.+>/';
                        preg_match($sub_pattern, $img, $res);
                        if ($res && is_array($res)){
                            $relative_id_hash[$res[1]][] = $res[2];
                        }
                    }

                    if ($relative_id_hash && is_array($relative_id_hash)) {
                        $relative_ids = [];
                        if ($relative_id_hash['article'] && is_array($relative_id_hash['article'])) {
                            $relative_ids = array_merge($relative_ids, $relative_id_hash['article']);
                        }
                        if ($relative_id_hash['guide'] && is_array($relative_id_hash['guide'])) {
                            $relative_ids = array_merge($relative_ids, $relative_id_hash['guide']);
                        }
                        if ($relative_id_hash['blank'] && is_array($relative_id_hash['blank'])) {
                            $relative_ids = array_merge($relative_ids, $relative_id_hash['blank']);
                        }
                        if ($relative_id_hash['answer'] && is_array($relative_id_hash['answer'])) {
                            $relative_ids = array_merge($relative_ids, $relative_id_hash['answer']);
                        }

                        // 判断在专题和文章关系中是否存有记录，如果有记录说明是修改已发布专题，否则是第一次发布专题
                        $relation_data = SitemRelevance::select('*', ['main_id' => $guide_id]);
                        if ($relation_data && is_array($relation_data)) {
                            $relatived_ids = array_map(function ($v){
                                return $v['obj_id'];
                            }, $relation_data);

                            // 对比上一个版本新增的文章
                            $add_relative_ids = array_diff($relative_ids, $relatived_ids);

                            if ($add_relative_ids && is_array($add_relative_ids)) {
                                foreach ($add_relative_ids as $relative_id) {
                                    if(!in_array($guide_id.'-'.IdParse::getUid($relative_id),$this->getSendData())) {
                                        if ($this->getReleteType($relative_id) == 1){
                                            \Doraemon\cache\Queue::insertQueue('queue/Sysmsg/Send', [
                                                'msgCode' => 107,
                                                'to_uid' => IdParse::getUid($relative_id),
                                                'msgParams' => [
                                                    'article_id' => $relative_id,
                                                    'guide_id' => $guide_id,
                                                    'zh_nick' => $zh_nick
                                                ]
                                            ], \Doraemon\cache\Queue::QUEUE_DORAEMON);

                                            $this->addSendUidsByGuide($guide_id, IdParse::getUid($relative_id));
                                        }

                                        if (($this->getReleteType($relative_id) == 6) || ($this->getReleteType($relative_id) == 4)){
                                            \Doraemon\cache\Queue::insertQueue('queue/Sysmsg/Send', [
                                                'msgCode' => 108,
                                                'to_uid' => IdParse::getUid($relative_id),
                                                'msgParams' => [
                                                    'link' => HhzNiceLivingUrl::getSpecialItemDetailLink($guide_id),
                                                    'guide_id' => $guide_id,
                                                    'zh_nick' => $zh_nick
                                                ]
                                            ], \Doraemon\cache\Queue::QUEUE_DORAEMON);
                                            $this->addSendUidsByGuide($guide_id, IdParse::getUid($relative_id));
                                        }

                                        if ($this->getReleteType($relative_id) == 5){
                                            \Doraemon\cache\Queue::insertQueue('queue/Sysmsg/Send', [
                                                'msgCode' => 116,
                                                'to_uid' => IdParse::getUid($relative_id),
                                                'msgParams' => [
                                                    'link' => HhzNiceLivingUrl::getSpecialItemDetailLink($guide_id),
                                                    'blank_id' => $relative_id,
                                                    'guide_id' => $guide_id,
                                                    'zh_nick' => $zh_nick
                                                ]
                                            ], \Doraemon\cache\Queue::QUEUE_DORAEMON);
                                            $this->addSendUidsByGuide($guide_id, IdParse::getUid($relative_id));
                                        }
                                    }


                                    $article_join_data = [];
                                    $article_join_data['main_id'] = $guide_id;
                                    $article_join_data['obj_id'] = $relative_id;
                                    $article_join_data['type'] = $this->getReleteType($relative_id);
                                    $article_join_data['addtime'] = time();
                                    SitemRelevance::insert($article_join_data);
                                }
                            }
                            // 对比上一个版本删除的文章
                            $del_article_ids = array_diff($relatived_ids, $relative_ids);
                            if ($del_article_ids && is_array($del_article_ids)) {
                                foreach ($del_article_ids as $article_id) {
                                    $where = [];
                                    $where['main_id'] = $guide_id;
                                    $where['obj_id'] = $article_id;
                                    $where['type'] = $this->getReleteType($article_id);
                                    SitemRelevance::delete($where);
                                }
                            }
                        } else {
                            foreach ($relative_ids as $relative_id) {
//                                if ($data['type'] == '0'){
//
//                                }
                                if(!in_array($guide_id.'-'.IdParse::getUid($relative_id),$this->getSendData())) {
                                    if ($this->getReleteType($relative_id) == 1) {
                                        \Doraemon\cache\Queue::insertQueue('queue/Sysmsg/Send', [
                                            'msgCode' => 107,
                                            'to_uid' => IdParse::getUid($relative_id),
                                            'msgParams' => [
                                                'article_id' => $relative_id,
                                                'guide_id' => $guide_id,
                                                'zh_nick' => $zh_nick
                                            ]
                                        ], \Doraemon\cache\Queue::QUEUE_DORAEMON);

                                        $this->addSendUidsByGuide($guide_id, IdParse::getUid($relative_id));
                                    }

                                    if (($this->getReleteType($relative_id) == 6) || ($this->getReleteType($relative_id) == 4)) {
                                        \Doraemon\cache\Queue::insertQueue('queue/Sysmsg/Send', [
                                            'msgCode' => 108,
                                            'to_uid' => IdParse::getUid($relative_id),
                                            'msgParams' => [
                                                'link' => HhzNiceLivingUrl::getSpecialItemDetailLink($guide_id),
                                                'guide_id' => $guide_id,
                                                'zh_nick' => $zh_nick
                                            ]
                                        ], \Doraemon\cache\Queue::QUEUE_DORAEMON);

                                        $this->addSendUidsByGuide($guide_id, IdParse::getUid($relative_id));
                                    }

                                    if ($this->getReleteType($relative_id) == 5) {
                                        \Doraemon\cache\Queue::insertQueue('queue/Sysmsg/Send', [
                                            'msgCode' => 116,
                                            'to_uid' => IdParse::getUid($relative_id),
                                            'msgParams' => [
                                                'link' => HhzNiceLivingUrl::getSpecialItemDetailLink($guide_id),
                                                'blank_id' => $relative_id,
                                                'guide_id' => $guide_id,
                                                'zh_nick' => $zh_nick
                                            ]
                                        ], \Doraemon\cache\Queue::QUEUE_DORAEMON);

                                        $this->addSendUidsByGuide($guide_id, IdParse::getUid($relative_id));
                                    }
                                }
                                $article_join_data = [];
                                $article_join_data['main_id'] = $guide_id;
                                $article_join_data['obj_id'] = $relative_id;
                                $article_join_data['type'] = $this->getReleteType($relative_id);
                                $article_join_data['addtime'] = time();
                                SitemRelevance::insert($article_join_data);
                            }
                        }
                    }
                }
            }
            // 查询文章发布信息，如果已发布过,那么更新数据,如果没有发布过,那么添加发布

            $publish_guide_data = PublishGuide::get('*', ['id' => $guide_id]);
            unset($guide['cron_date']);


            if ($publish_guide_data && is_array($publish_guide_data)) {
                //专题类型为指南时添加标签信息
                if ($guide['type'] == 0) {
                    $old_admin_tags = array_map('trim', explode(',', $publish_guide_data['admin_tag']));
                    $new_admin_tags = array_map('trim', explode(',', $guide['admin_tag']));
                    $add_tags = array_diff($new_admin_tags, $old_admin_tags);
                    $del_tags = array_diff($old_admin_tags, $new_admin_tags);
                    TagGuideCounter::incrMulti($add_tags);
                    TagGuideCounter::decrMulti($del_tags);
                }

                $resouce_main_tag_arr = trim($publish_guide_data['main_tag']) ? explode(",", $publish_guide_data['main_tag']) : [];
                $target_main_tag_arr = trim($guide['main_tag']) ? explode(",", $guide['main_tag']) : [];

                $resource_diff = array_diff($resouce_main_tag_arr, $target_main_tag_arr);
                $target_diff = array_diff($target_main_tag_arr, $resouce_main_tag_arr);

                //专题或者指南有主标签
                if (is_array($resource_diff) && $resource_diff  && ($guide['type'] == 0 || $guide['type'] == 2)) {
                    foreach ($resource_diff as $r_diff) {
                        MainTag::handleEditMainTag(trim($r_diff), $guide_id);
                    }
                }

                if (is_array($target_diff) && $target_diff && ($guide['type'] == 0 || $guide['type'] == 2)) {
                    foreach ($target_diff as $t_diff) {
                        MainTag::handleEditMainTag(trim($t_diff), $guide_id);
                    }
                }

                $publish_data = $guide;
                unset($publish_data['addtime']);
                $publish_data['status'] = PublishGuide::STATUS_NORMAL;
                PublishGuide::updateById($guide_id, $publish_data);
            } else {
                if ($guide['admin_tag']) {
                    $add_tags = array_map('trim', explode(',', $guide['admin_tag']));
                    TagGuideCounter::incrMulti($add_tags);
                }

                //专题或者指南有主标签
                if ($guide['main_tag']  && ($guide['type'] == 0 || $guide['type'] == 2)) {
                    $main_tag_arr = explode(",", $guide['main_tag']);
                    foreach ($main_tag_arr as $main_tag) {
                        MainTag::handleEditMainTag(trim(trim($main_tag)), $guide_id);
                    }
                }
                $publish_data = $guide;
                $publish_data['addtime'] = time();
                $publish_data['status'] = PublishGuide::STATUS_NORMAL;

//                // 指南加入动态,专题不加
//                if($data['type'] == 0) {
//
//                }
                \Doraemon\cache\Queue::insertQueue('Dynamic/addGuideDynamic', ['obj_id' => $guide_id]);
                PublishGuide::insert($publish_data);
            }

            // 当专题打上#新手装修, #新手居家标签时。需要保存到一个库，作为新用户推荐
//            if ($data['type'] == 2) {
//                $this->submitToRecommendPool($data);
//            }

            //专题类型为指南时添加banner
//            if ($data['type'] == '0') {
                // 发布的时候推广告
                if (!AdmSpecialBanner::get('id', ['unique_id' => $guide_id])) {
                    $spec_banner_addtime = isset($publish_guide_data['addtime']) ? $publish_guide_data['addtime'] : time();
                    $aData = [];
                    $aData['pic_id'] = $guide['cover_pic_id_2_0'];
                    $aData['link_type'] = 'guide';
                    $aData['unique_id'] = $guide_id;
                    $aData['link_dest'] = $guide_id;
                    $aData['addtime'] = $spec_banner_addtime;
                    $aData['detail'] = '第 ' . $guide['number'] . ' 期 ' . date('Y.m.d', $spec_banner_addtime) . ' 发布';
                    AdmSpecialBanner::addBanner($guide['title'], $aData);
                }
//            }

            //关联wiki
            $wikis = (array) sGuide::getWikiIds($guide['content']);
            \Biz\service\wiki\ObjRelateWiki::guideRelateWiki($guide['uid'],$guide['id'], $wikis);


            // 修改文章状态
            mGuide::updateGuide($guide_id, ['status' => mGuide::STATUS_NORMAL]);
//
//            $oQueue = new QueueModel();
//            if($data['status'] == GuideModel::STATUS_DRAFT){
//                if ($data['type'] == 0) {
//                    //     $oQueue->insertQueue('Api/jike_publish', array(
//                    // 'guide_id' => $guide_id
//                    //  ));
//                }
//            }
//            if($data['type']==0){
            \Doraemon\cache\Queue::insertQueue('TotalArticle/updateTotalArticle', ['article_id' => $guide_id]);
            \Doraemon\cache\Queue::insertQueue('TotalArticle/updateTotalArticle',['article_id' => $guide_id]);
//            }
            \Doraemon\cache\Queue::insertQueue('Guide/updateSolr', ['guide_id' => $guide_id]);

            //更新wiki计数
            \Doraemon\amqp\Queue::insertQueue('queue/wiki/setWikisNumByObjId', array(
                'obj_id' => $guide_id,
                'obj_type'=>\Biz\model\wiki\ObjRelateWiki::OBJ_TYPE_GUIDE
            ), \Doraemon\amqp\Queue::QUEUE_BIZ);

            $data['code'] = 200;
            $data['msg'] = '发布成功！';
            return $data;
        } catch (\Exception $e) {
            $data['code'] = 400;
            $data['msg'] = $e->getMessage();
            return $data;
        }
    }

    // 定时发布专题
    public function cronPublish(Request $request, Content $content, $id)
    {
        if ($request->method() === 'POST') {
            $params = $request->all();
            $date = $params['cron_date'];
            $hour = $params['cron_hour'];

            if(strpos($hour, '.')) {
                $publish_date = $date . ' ' . str_replace('.5','',$hour). ':30:00';
            } else {
                $publish_date = $date . ' ' . str_pad($hour, 2, 0, STR_PAD_LEFT) . ':00:00';
            }

            $publish_date = strtotime($publish_date);
            if ($publish_date < time()) {
                $publish_date = 0;
            }
            $result = mGuide::updateGuide($id, ['cron_date' => $publish_date]);

            if ($result) {
                $success = new MessageBag([
                    'title' => '操作成功'
                ]);
                return redirect('/admin/guide/listing')->with(compact('success'));
            } else {
                $error = new MessageBag([
                    'title' => '操作失败'
                ]);
                return redirect('/admin/guide/listing')->with(compact('error'));
            }
        } else {
//        $form->html('<h7>'.date( "Y-m-d",$data['show_time']).' </h7>',
            $data = mGuide::getGuide($id);
            if ($data) {
                $cron_publish_date = $data['cron_date'];

                $data['cron_date'] = date('Y-m-d', time());
                $data['cron_hour'] = '';
                if ($cron_publish_date !== '0' && date('Y-m-d H:i:s', $cron_publish_date)) {
                    $data['cron_date'] = date('Y-m-d', $cron_publish_date);
                    $data['cron_hour'] = date('H', $cron_publish_date);
                }
                $hours = [];
                for ($i = 0; $i < 24; $i=$i+0.5) {
                    $hours["$i"] = $i;
                }

                $form = new Form($data);

                $form->text('id', '专题id')->disable();
//                $form->hidden('guide_id')->value($id);
                $form->text('title', '文章标题')->disable();
                $form->date('cron_date', '发布日期')->format('YYYY-MM-DD');
                $form->select('cron_hour', '发布时间')->options($hours)->help("小时");
                $form->action('/admin/guide/listing/cron/publish/'.$id);
                return $content
                    ->row($form->render());
            }
        }
    }


    // 处理图片关联文章
    // 给用户发消息，添加图片和专题的关系(已经删除专题相关操作， 只留下type=0的指南)
    private function handlePhotoRelation($photo_ids, $guide_id, $uid = 0)
    {
        if (empty($photo_ids) || ! is_array($photo_ids)) {
            return false;
        }

        //获取指南创建者
        $zh_nick = sGuide::AUTHERS[$uid] ?? "好好住";

        foreach ($photo_ids as $photo_id) {
            $photo_join_data = [];
            $photo_join_data['photo_id'] = $photo_id;
            $photo_join_data['guide_id'] = $guide_id;
            $photo_join_data['addtime'] = time();
            PhotoJoinGuide::insert($photo_join_data);
            $uid = IdParse::getUid($photo_id);
            if(!in_array($guide_id.'-'.$uid,$this->getSendData())) {
                \Doraemon\cache\Queue::insertQueue('queue/Sysmsg/Send', [
                    'msgCode' => 104,
                    'to_uid' => $uid,
                    'msgParams' => [
                        'link' => HhzNiceLivingUrl::getSpecialItemDetailLink($guide_id),
                        'photo_id' => $photo_id,
                        'guide_id' => $guide_id,
                        'zh_nick' => $zh_nick
                    ]
                ], \Doraemon\cache\Queue::QUEUE_DORAEMON);
                $this->addSendUidsByGuide($guide_id, $uid);
            }
            // 删除图片信息缓存
            \Doraemon\cache\Queue::insertQueue('Photo/delCacheById', ['photo_id' => $photo_id]);
        }
        return true;
    }

    public function getSendData()
    {
        $data = [];
        if(file_exists(self::GUIDE_SEND_MSG)) {
            $data = explode(PHP_EOL, file_get_contents(self::GUIDE_SEND_MSG));
        }
        return $data;
    }

    public function addSendUidsByGuide($guide_id, $uid)
    {
        if(file_exists(self::GUIDE_SEND_MSG)) {
            file_put_contents(self::GUIDE_SEND_MSG, $guide_id.'-'.$uid.PHP_EOL, FILE_APPEND);
        }
        return true;
    }

    private function getReleteType($obj_id){
        $type = 0;
        switch (substr($obj_id, 7, 2)) {
            case '01':
                $type = 1;
                break;
            case '02':
                $type = 2;
                break;
            case '04':
                $type = 4;
                break;
            case '05':
                $type = 5;
                break;
            case '00':
                $type = 6;
                break;
            default:
                break;
        }
        return $type;
    }

}